package com.sdy.healthcode.biz.utils;

import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import org.springframework.beans.BeanUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 通过身份证获取人员详细信息的util
 *
 * @author hyh
 */
public class IdCardUtil {

    /**
     * 根据身份证号获取性别信息
     *
     * @param idCard
     * @return
     */
    public static String getSexByIdCard(String idCard) throws BizException {
        Assert.isTrue(!isValidate18IdCard(idCard), "非法身份证号码");
        // 已知身份证号第17位数字为性别，奇数为男性、偶数为女性
        String sexStr = idCard.substring(16, 17);
        return Integer.parseInt(sexStr) % 2 == 0 ? "女" : "男";
    }

    /**
     * 根据生日计算年龄
     */
    public static Integer getAgeByDateString(String idCard) throws BizException, ParseException {
        Assert.isTrue(!isValidate18IdCard(idCard), "非法身份证号码");
        String dateStr = idCard.substring(6, 14);
        // 身份证号码上面的日期
        Date idDate = new SimpleDateFormat("yyyyMMdd").parse(dateStr);
        // 初始化
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        calendar.setTime(idDate);
        int idYear = calendar.get(Calendar.YEAR);
        int idMonth = calendar.get(Calendar.MONTH) + 1;
        int idDay = calendar.get(Calendar.DAY_OF_MONTH);
        int age = year - idYear;
        if (month <= idMonth && month == idMonth && day < idDay || month < idMonth) {
            age--;
        }
        return age;
    }

    /**
     * @param idCard
     * @return
     */
    public static boolean isValidate18IdCard(String idCard) {
        // 判断身份证长度是否是18位
        if (idCard.length() != 18) {
            return false;
        }
        return true;
    }
}
